package com.ruoyi.web.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.TokenService;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.JakartaServletUtil;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

/***
 * 数据增强过滤器，增加一些默认字段*
 * 
 * @author lincm*
 * @date 2022/11/04
 */
@Slf4j
@Component
public class EnhanceFilter implements Filter {

    public static final String SYSUSERID = "sysUserId";
    public static final String LOGINIP = "loginIp";
    public static final String ACCEPT_LANGUAGE = "Accept-Language";

    @Autowired
    private TokenService tokenService;

    public static final Set<String> whileList = new HashSet<String>() {

        private static final long serialVersionUID = 1L;
        {
            add("/client/wx/pay/v3/payNotify");
            add("/client/cli/stripe/co/v1/webhook");
        }
    };

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        log.info("EnhanceFilter>>>>" + httpServletRequest.getRequestURI());
        if (whileList.contains(httpServletRequest.getRequestURI())) {
            log.info("EnhanceFilter>>>>JUMP");
            chain.doFilter(request, response);
        } else {
            String token = tokenService.getToken(httpServletRequest);

            HashMap<String, String[]> parameterMap = new HashMap<String, String[]>(request.getParameterMap());
            parameterMap.put(LOGINIP, new String[] {JakartaServletUtil.getClientIP((HttpServletRequest)request)});

            if (StrUtil.isNotBlank(token)) {
                LoginUser loginUser = tokenService.getLoginUser(httpServletRequest);
                if (ObjUtil.isNotNull(loginUser)) {
                    // CliUserContextUtil.setCurrentUser(basicUser);
                    parameterMap.put(SYSUSERID, new String[] {String.valueOf(loginUser.getUserId())});
                }
                ServletRequest newRequest = new ExtRequestWrapper((HttpServletRequest)request, parameterMap);
                chain.doFilter(newRequest, response);
            } else {
                chain.doFilter(request, response);
            }
        }
    }
}
